package cytj.setup.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import cytj.setup.R;
import cytj.setup.adapter.DataReceiveAdapter;
import cytj.setup.base.MessageWhat;
import cytj.setup.base.MyAPP;
import cytj.setup.bean.Data;
import cytj.setup.bluetooth.BluetoothService;
import cytj.setup.fragment.BaseSetupFragment;
import cytj.setup.fragment.DataReceiveFragment;
import cytj.setup.fragment.NodesDeployFragment;
import cytj.setup.fragment.NodesSetupFragment;
import cytj.setup.util.CharacterTool;


/**
 * 主Activity，用于进行蓝牙连接并接受数据操作以及进行容纳BaseSetupFragment、NodesDeployFragment、NodesSetupFragment
 * Created by LTP on 2015/12/14
 */
public class SetupActivity extends Activity implements View.OnClickListener, RadioGroup.OnCheckedChangeListener {
    /**
     * 连接蓝牙的按键
     */
    private Button button_connectBluetooth;
    /**
     * 下面3个切换Fragment的RadioButton
     */
    private RadioButton radioButton_baseSetup, radioButton_nodesDeploy, radioButton_nodesSetup, radioButton_dataReceive;
    /**
     * 基站配置Fragment的对象
     */
    private BaseSetupFragment baseSetupFragment;
    /**
     * 节点部署Fragment的对象
     */
    private NodesDeployFragment nodesDeployFragment;
    /**
     * 节点设置Fragment的对象
     */
    private NodesSetupFragment nodesSetupFragment;
    private DataReceiveFragment dataReceiveFragment;
    private FragmentManager fragmentManager;
    private BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    private BluetoothDevice bluetoothDevice;
    public ArrayList<Data> dataList;
    public DataReceiveAdapter adapter;
    /**
     * 蓝牙操作相关类对象
     */
    public BluetoothService bluetoothService;
    public ProgressDialog progressDialog;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MessageWhat.CONNECT_BLUETOOTH_SUCCESS:
                    Toast.makeText(SetupActivity.this, "已连接到:" + bluetoothDevice.getName(), Toast.LENGTH_SHORT).show();
                    button_connectBluetooth.setText("断开连接");
                    MyAPP.getMyAPPInstance().setIsBluetoothConnected(true);
                    break;
                case MessageWhat.CONNECT_BLUETOOTH_FAILED:
                    Toast.makeText(SetupActivity.this, "连接" + bluetoothDevice.getName() + "失败", Toast.LENGTH_SHORT).show();
                    button_connectBluetooth.setText("连接蓝牙");
                    MyAPP.getMyAPPInstance().setIsBluetoothConnected(false);
                    break;
                case MessageWhat.BLUETOOTH_CONNECTION_LOST:
                    Toast.makeText(SetupActivity.this, "与蓝牙" + bluetoothDevice.getName() + "已断开！", Toast.LENGTH_SHORT).show();
                    button_connectBluetooth.setText("连接蓝牙");
                    MyAPP.getMyAPPInstance().setIsBluetoothConnected(false);
                    break;
                case MessageWhat.READ_BASE_DATA_SUCCESS:
                    String data = (String) msg.obj;
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(SetupActivity.this, "读取成功", Toast.LENGTH_SHORT).show();
                    baseSetupFragment.baseSetupCountDownTimer.cancel();
                    parseData(data);
                    break;
                case MessageWhat.WRITE_BASE_DATA_SUCCESS:
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(SetupActivity.this, "写入成功", Toast.LENGTH_SHORT).show();
                    baseSetupFragment.baseSetupCountDownTimer.cancel();
                    break;
                case MessageWhat.DEPLOY_BASE_COMMUNICATION_SUCCESS:
                    data = (String) msg.obj;
                    if (data.length() == 24) {
                        Toast.makeText(SetupActivity.this, "基站工作正常", Toast.LENGTH_SHORT).show();
                        String deployBaseID = data.substring(4, 10);
                        nodesDeployFragment.setEditText_showDeployBaseID(deployBaseID);
                    } else if (data.length() == 22) {
                        Toast.makeText(SetupActivity.this, "节点编码获取成功", Toast.LENGTH_SHORT).show();
                        String nodesID = data.substring(16, 22);
                        nodesDeployFragment.setEditText_showNodesID(nodesID);
                    }
                    break;
                case MessageWhat.DEPLOY_NODES_SUCCESS:
                    data = (String) msg.obj;
                    Toast.makeText(SetupActivity.this, "部署成功", Toast.LENGTH_LONG).show();
                    nodesDeployFragment.setButton_deployNodes();
                    nodesDeployFragment.nodesDeployCountDownTimer.cancel();
                    String requestProtocol = "ABAB" + data + "F100";
                    requestProtocol += CharacterTool.xor(CharacterTool.hexStringToBytes(requestProtocol), CharacterTool.hexStringToBytes(requestProtocol).length);
                    bluetoothService.write(CharacterTool.hexStringToBytes(requestProtocol));
                    break;
                case MessageWhat.SET_NODES_SLEEP_SUCCESS:
                    data = (String) msg.obj;
                    nodesSetupFragment.setShowBaseID(data.substring(4, 10));
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(SetupActivity.this, "设定节点休眠成功", Toast.LENGTH_LONG).show();
                    nodesSetupFragment.nodesSetupCountDownTimer.cancel();
                    break;
                case MessageWhat.RESTART_NODES_SUCCESS:
                    data = (String) msg.obj;
                    nodesSetupFragment.setShowBaseID(data.substring(4, 10));
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(SetupActivity.this, "节点重启成功！", Toast.LENGTH_LONG).show();
                    nodesSetupFragment.nodesSetupCountDownTimer.cancel();
                    break;
                case MessageWhat.CHANGE_NODES_STATUS_SUCCESS:
                    data = (String) msg.obj;
                    nodesSetupFragment.setShowBaseID(data.substring(4, 10));
                    if (progressDialog != null) {
                        progressDialog.dismiss();
                    }
                    Toast.makeText(SetupActivity.this, "纠正节点状态成功！", Toast.LENGTH_LONG).show();
                    nodesSetupFragment.nodesSetupCountDownTimer.cancel();
                    break;
                case MessageWhat.DATA_RECEIVED_SUCCESS:
                    data = (String) msg.obj;
                    String currentTime = (new SimpleDateFormat("yy-MM-dd HH:mm:ss", Locale.CHINA)).format(new Date());
                    Data data1 = new Data(data, currentTime);
                    dataList.add(data1);
                    Collections.sort(dataList);
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setup);
        openBluetooth();
        initView();
        setDefaultFragment();
    }

    /**
     * 通过提醒的方式打开蓝牙
     */
    private void openBluetooth() {
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "您的手机不支持蓝牙!", Toast.LENGTH_LONG).show();
            finish();
        } else if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 1);
        }
    }

    /**
     * 控件初始化
     */
    private void initView() {
        button_connectBluetooth = (Button) findViewById(R.id.button_connectBluetooth_setupActivity);
        button_connectBluetooth.setOnClickListener(this);
        // 容纳RadioButton的radioGroup
        RadioGroup radioGroup_tab = (RadioGroup) findViewById(R.id.radioGroup_tab_setupActivity);
        radioGroup_tab.setOnCheckedChangeListener(this);
        radioButton_baseSetup = (RadioButton) findViewById(R.id.radioButton_baseSetup_setupActivity);
        radioButton_nodesDeploy = (RadioButton) findViewById(R.id.radioButton_nodesDeploy_setupActivity);
        radioButton_nodesSetup = (RadioButton) findViewById(R.id.radioButton_nodesSetup_setupActivity);
        radioButton_dataReceive = (RadioButton) findViewById(R.id.radioButton_dataReceive_setupActivity);
    }

    /**
     * 设置SetupActivity启动时默认加载的Fragment，以及初始化三个Fragment
     */
    private void setDefaultFragment() {
        baseSetupFragment = new BaseSetupFragment();
        nodesDeployFragment = new NodesDeployFragment();
        nodesSetupFragment = new NodesSetupFragment();
        dataReceiveFragment = new DataReceiveFragment();
        dataList = new ArrayList<>();
        adapter = new DataReceiveAdapter(this, R.layout.listview_item_data_receive, dataList);
        fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frameLayout_fargments_setupActivity, baseSetupFragment);
        fragmentTransaction.commit();
    }

    /**
     * 显示进度提示框
     *
     * @param text 设置进度框的进度
     */
    public void showProgressDialog(String text) {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage(text);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();
    }

    /**
     * 将接收到的数据按协议解析
     *
     * @param readString 接受的数据
     */
    private void parseData(String readString) {
        String baseID = readString.substring(4, 10);
        baseSetupFragment.setEditText_showBaseID(baseID);
        String baseType = readString.substring(26, 28);
//        Log.d(TAG, "基站类型:" + baseType);
        baseSetupFragment.setBaseType(baseType);
        String frequency = readString.substring(28, 34);
//        Log.d(TAG, "无线载波频率:" + frequency);
        baseSetupFragment.setFrequencyText(Integer.parseInt(frequency, 16) + "");
        String targetIP = readString.substring(36, 44);
//        Log.d(TAG, "目标IP:" + targetIP);
        String targetIP2 = parseIP(targetIP);
        baseSetupFragment.setTargetIPText(targetIP2);
        String targetCom = readString.substring(44, 48);
//        Log.d(TAG, "目标端口:" + targetCom);
        baseSetupFragment.setTargetComText(Integer.parseInt(targetCom, 16) + "");
        String baseIP = readString.substring(48, 56);
//        Log.d(TAG, "基站IP:" + baseIP);
        String baseIP2 = parseIP(baseIP);
        baseSetupFragment.setBaseIPText(baseIP2);
        String baseCom = readString.substring(56, 60);
//        Log.d(TAG, "基站端口:" + baseCom);
        baseSetupFragment.setBaseComText(Integer.parseInt(baseCom, 16) + "");
        String gatewayIP = readString.substring(60, 68);
//        Log.d(TAG, "网关IP:" + gatewayIP);
        String gatewayIP2 = parseIP(gatewayIP);
        baseSetupFragment.setGatewayIPText(gatewayIP2);
        String treaty = readString.substring(66, 68);
//        Log.d(TAG, "协议类型:" + treaty);
        baseSetupFragment.setTreaty(treaty);
    }

    /**
     * 解析IP地址数据
     *
     * @param IP 四个字节表示的IP地址
     * @return IP地址
     */
    private String parseIP(String IP) {
        return Integer.parseInt(IP.substring(0, 2), 16) + "." + Integer.parseInt(IP.substring(2, 4), 16) + "." +
                Integer.parseInt(IP.substring(4, 6), 16) + "." +
                Integer.parseInt(IP.substring(6, 8), 16);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_connectBluetooth_setupActivity:
                //点击连接蓝牙按键
                if (bluetoothAdapter.isEnabled()) {
                    if (MyAPP.getMyAPPInstance().isBluetoothConnected()) {
                        bluetoothService.stop();
                        button_connectBluetooth.setText("连接蓝牙");
                    } else {
                        Intent intent = new Intent(this, BluetoothDeviceListActivity.class);
                        startActivityForResult(intent, 2);
                    }
                } else {
                    openBluetooth();
                }
                break;
        }
    }

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO radioGroup下radioButton点击改变的回调
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        switch (checkedId) {
            case R.id.radioButton_baseSetup_setupActivity:
                // 点击基站配置的radioButton
                radioButton_baseSetup.setBackgroundResource(R.color.orange);
                radioButton_nodesDeploy.setBackgroundResource(R.color.white);
                radioButton_nodesSetup.setBackgroundResource(R.color.white);
                radioButton_dataReceive.setBackgroundResource(R.color.white);
                if (baseSetupFragment == null) {
                    baseSetupFragment = new BaseSetupFragment();
                }
                fragmentTransaction.replace(R.id.frameLayout_fargments_setupActivity, baseSetupFragment);
                break;
            case R.id.radioButton_nodesDeploy_setupActivity:
                // 点击节点部署的radioButton
                radioButton_baseSetup.setBackgroundResource(R.color.white);
                radioButton_nodesDeploy.setBackgroundResource(R.color.orange);
                radioButton_nodesSetup.setBackgroundResource(R.color.white);
                radioButton_dataReceive.setBackgroundResource(R.color.white);
                if (nodesDeployFragment == null) {
                    nodesDeployFragment = new NodesDeployFragment();
                }
                fragmentTransaction.replace(R.id.frameLayout_fargments_setupActivity, nodesDeployFragment);
                break;
            case R.id.radioButton_nodesSetup_setupActivity:
                // 点击节点设置的radioButton
                radioButton_baseSetup.setBackgroundResource(R.color.white);
                radioButton_nodesDeploy.setBackgroundResource(R.color.white);
                radioButton_nodesSetup.setBackgroundResource(R.color.orange);
                radioButton_dataReceive.setBackgroundResource(R.color.white);
                if (nodesSetupFragment == null) {
                    nodesSetupFragment = new NodesSetupFragment();
                }
                fragmentTransaction.replace(R.id.frameLayout_fargments_setupActivity, nodesSetupFragment);
                break;
            case R.id.radioButton_dataReceive_setupActivity:
                // 点击数据接收的radioButton
                radioButton_baseSetup.setBackgroundResource(R.color.white);
                radioButton_nodesDeploy.setBackgroundResource(R.color.white);
                radioButton_nodesSetup.setBackgroundResource(R.color.white);
                radioButton_dataReceive.setBackgroundResource(R.color.orange);
                if (dataReceiveFragment == null) {
                    dataReceiveFragment = new DataReceiveFragment();
                }
                fragmentTransaction.replace(R.id.frameLayout_fargments_setupActivity, dataReceiveFragment);
                break;
        }
        fragmentTransaction.commit();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 从下一个页面返回的数据
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1:
                //开启蓝牙的返回
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show();
                } else {
                    finish();
                }
                break;
            case 2:
                if (resultCode == RESULT_OK) {
                    //点击连接蓝牙设备后的返回
                    button_connectBluetooth.setText("正在连接...");
                    String bluetoothMacAddress = data.getStringExtra("macAddress");
                    bluetoothDevice = bluetoothAdapter.getRemoteDevice(bluetoothMacAddress);
                    bluetoothService = new BluetoothService(handler);
                    bluetoothService.connect(bluetoothDevice);
                }
            default:
                break;
        }
    }

    // 是否退出程序
    private static Boolean isExit = false;
    // 定时触发器
    private static Timer timer = null;

    @Override
    public void onBackPressed() {
        // TODO 重写onBackPressed(返回键)实现两次点击才退出程序
        // super.onBackPressed();
        if (!isExit) {
            isExit = true;
            if (timer != null) {
                timer.cancel(); // 将原任务从队列中移除
            }
            // 重新实例一个定时器
            timer = new Timer();
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                    isExit = false;
                }
            };
            Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
            // 延时两秒触发task任务
            timer.schedule(task, 2000);
        } else {
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        // TODO 销毁Activity时（退出程序时）停止蓝牙相关线程
        super.onDestroy();
        if (bluetoothService != null) {
            bluetoothService.stop();
        }
    }

}
